import request from '../utils/request.jsx';

/**
 * 获取用户信息
 * @returns {Promise}
 */
export async function getUserInfo() {
  try {
    const response = await request.get('/auth-center/auth/info');
    // 直接返回用户信息对象
    return response.data;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    // 返回null表示获取失败
    return null;
  }
}

/**
 * 登录
 * @param {Object} credentials - 登录凭证
 * @param {string} credentials.username - 用户名
 * @param {string} credentials.password - 密码
 * @returns {Promise}
 */
export async function login(credentials) {
  try {
    return await request.post('/auth-center/auth/login', credentials);
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
}

/**
 * 退出登录
 * @returns {Promise}
 */
export async function logout() {
  try {
    const response = await request.post('/auth-center/auth/logout');
    // 清除本地存储的token和用户信息
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    return response;
  } catch (error) {
    console.error('退出登录失败:', error);
    // 即使请求失败，也清除本地存储
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    throw error;
  }
}

/**
 * 注册
 * @param {Object} userInfo - 用户信息
 * @returns {Promise}
 */
export async function register(userInfo) {
  try {
    return await request.post('/auth-center/auth/register', userInfo);
  } catch (error) {
    console.error('注册失败:', error);
    throw error;
  }
}